<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 10:17
 */
namespace app\admin\model;

use think\Model;
use think\Db;
use app\admin\controller\Product;
class OrderModel extends Model
{
    // 确定链接表名order 附表 : account (流水)
    protected $name = 'order';

    //  订单录入
    /*
     * Array
     */
    public function getOrderAdd ($param)
    {
        $this::startTrans();
        try{
            $payment_method = (int)$param['payment_method'];//期数id
            $total_amount = $param['total_amount'];//总金额
            $method_num =Db::name('product_attr')->where(['id'=>$payment_method])->value('values');
            //每期金额
            $total_mon = (int)$total_amount / (int)$method_num;
            $assArr = [];
            $assArr['order_sn'] = $param['order_sn'];//关联单号
            $assArr['m_id'] = $param['m_id'];//客户ID
			$assArr['s_id'] = $param['consultant'];//关联人id
            $assArr['total_amount'] = $total_mon; //流水金额
            $assArr['status'] = 0; //流水状态
            $assArr['c_time'] = $param['c_time'];//创建时间
            $assArr['finish_time'] = $param['c_time'];//完成时间(算)
            $assArr['create_uid'] = $param['create_uid'];//创建者id
			$assArr['agent'] = $param['create_uid'];//经办人id
            $result = $this->validate('OrderValidate')->save($param);
            Db::name('member')->where(['id'=>$param['m_id']])->update(['status' => 2]);
            $this->accOdrAdd($assArr , (int)$method_num);
            $this::commit();
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{
                return msg(1, url('member/memberList'), '添加成功');
            }
        }catch(\Exception $e){
            $this::rollback();
            return msg(-2, '', $e->getMessage());
        }
    }
    /**
     * 增加流水
     *  $assArr (流水信息)
     * $payment_method(期数)
     */
    public function accOdrAdd ($assArr , $method_num)
    {
		$this::startTrans();
        try{
			for ($i=0; $i < $method_num; $i++) {
			  $payDate = Db::name('webset')->where(['name'=>'pay_date'])->value('values');
			  $Now = date('Y-m' , strtotime('+1 month'))."-".$payDate;
			  $finish_time = date('Y-m-d', strtotime($Now.' +'. $i .' month'));
			  $assArr['finish_time'] = strtotime($finish_time);
			  $result = Db::name('account')->insertGetId($assArr);
			  $account_sn = date("Ymd").$result;
			  DB::name('account')->where('id',$result)->update(['account_sn'=>$account_sn]);
			}
			$this::commit();
        }catch(\Exception $e){
			$this::rollback();
			$this->error("添加订单失败".$e->getMessage());
        }
    }
    /**
     * 查询产品列表
     */
    public function getProductList ($school_id,$major_id)
    {
        $proName = Db::name('product')->where(['school_id'=>$school_id,'major_id'=>$major_id])->field('name,id')->select();
        return $proName;
    }
    /**
     * 查询属性
     * $id
     */
    public  function getConfigList ($id)
    {
        $cofigArr = Db::name('product')->where(['id'=>$id])->field('attr_info')->select();

        $cofigArr = $cofigArr[0]['attr_info'];
        $product = new Product();
        $cofigArr = $product->translateProAttrInfo($cofigArr)['translation'];
        return $cofigArr;
    }
    /**
     * 查询订单列表
     * $where
     */
    public function orderList ($where, $offset, $limit)
    {
        $orderArr = $this->where($where)->where($this->whereCansee())->limit($offset, $limit)->order('id desc')->select();
        return $orderArr;
    }
    /**
     * 根据搜索条件获取所有的订单数量
     * @param $where
     */
    public function getAllOrder($where)
    {
        return $this->where($where)->count();
    }
    /**
     * 根据id修改的订单状态 发起退款
     * $param 条件
     * 生成退款流水
     */
    public function getGathering($param)
    {
        try{
            $orderId = $param['orderId'];//退款id
            $deleteNum = $param['deleteNum'];//退款金额
            $remarks = $param['remarks'];//退款备注
            $status_K = $this->where(['id'=>$orderId])->value('status');//

            $data['status'] = $status_K + 30;
            $data['update_time'] = time();
            $data['remarks'] = $remarks;

            $result = $this->where(['id'=>$orderId])->update($data);
            $order_ass = $this->where(['id'=>$orderId])->find();//获取单号
            $studentId = Db::name('student')->where('m_id',$order_ass['m_id'])->value('id');
            //添加退款流水
            $order_where = [
                'total_amount'  =>  (-1 * $deleteNum),       //退款金额
                'source'        =>  3,                      //流水来源
                'status'        =>  0,                      //流水状态
                'remarks'       =>  $remarks,               //退款备注
                'create_uid'    =>  session('id'),          //创建人
                'abnormal'      =>  1,                      //异常状态
                'agent'         =>  session('id'),          //经办人
                'order_sn'      =>  $order_ass['order_sn'], //订单号
                'm_id'          =>  $order_ass['m_id'],     //客户id
                'c_time'        =>  time(),                 //创建时间
                'finish_time'   =>  time(),                 //创建时间
            ];
            if($studentId){
                $order_where['s_id'] = $studentId;
                $order_where['s_role'] = 0;
            }
            $result_1 = Db::name('account')->insertGetId($order_where);
            $account_sn = date("Ymd").$result_1;
            $deleteSta  = DB::name('account')->where('id',$result_1)->update(['account_sn'=>$account_sn]);

            if(false === $result || $deleteSta == false){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{
                return msg(1, url('Finance/businOrder'), '已提交');
            }
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }
    /**
     * 根据id修改的订单状态 伪删除订单
     * $param 条件
     */
    public function delOrder ($param)
    {
        $ids = json_decode($param);
        try{
            foreach($ids as $v){
                $this->where('id',$v)->update(['delete_status' => 1]);
            }
            $this->commit();
            return ['code'=>1,'msg'=>'删除成功'];
        }catch(\Exception $e){
            $this->rollback();
            return ['code'=>0,'msg'=>'删除失败'.$e->getMessage()];
        }
    }


	/**
	 * 根据用户id查询订单列表
	 * $uid 用户id
	 */
    public function getMyOrder ($where, $offset, $limit)
    {
        $orderArr = $this->where($where)->limit($offset, $limit)->order('id desc')->select();
        return $orderArr;
    }
    /**
     * 根据订单id查询相对应的订单详情详情
     * $id 订单id
     */
    public function getOrderInfo($id)
    {
        $orderA = $this->where('id',$id)->find();
        $ass_A = Db::name('account')->where('order_sn',$orderA['order_sn'])->select();
        //流水详情
        foreach ($ass_A as $key=>&$val){
            //流水状态
            switch (intval($val['status'])){
                case 0:
                    $val['status'] = '未支付';
                    break;
                case 1:
                    $val['status'] = '已支付';
                    break;
                case 2:
                    $val['status'] = '已逾期';
                    break;
                case 3:
                    $val['status'] = '已拒绝';
                    break;
                case 4:
                    $val['status'] = '同意';
                    break;
                case 5:
                    $val['status'] = '已取消';
                    break;
            }
            //创建时间
            if(empty($val['c_time'])){
                $val['c_time'] = 0;
            }else{
                $val['c_time'] = date('Y-m-d',$val['c_time']);
            }
            //更新时间
            if(empty($val['update_time'])){
                $val['update_time'] = 0;
            }else{
                $val['update_time'] = date('Y-m-d',$val['update_time']);
            }

            //完成时间
            if (empty($val['finish_time'])){
                $val['finish_time'] = 0;
            }else{
                $val['finish_time'] = date('Y-m-d',$val['finish_time']);
            }
            //创建人
            $val['create_name']  = Db::name('user')->where('id',$val['create_uid'])->value('real_name');
            //经办人
            $val['agent']  = Db::name('user')->where('id',$val['agent'])->value('real_name');
            //流水异常处理
            if ($val['abnormal'] == 0){
                $val['abnormal'] = '正常';
            }else{
                $val['abnormal'] = '异常';
            }
        }
        $orderA['account'] = $ass_A;
        return $orderA;
    }

    /**
     * 根据id条件恢复订单
     * @param $where
     */
    public function recoveryOrd ($param)
    {
        try{
            foreach($param as $v){
                $this->where('id',$v)->update(['delete_status' => 0]);
            }
            $this->commit();
            return ['code'=>1,'msg'=>'恢复成功'];
        }catch(Exception $e){
            $this->rollback();
            return ['code'=>0,'msg'=>'恢复失败'.$e->getMessage()];
        }
    }
    /**
     * 根据id条件删除订单
     * @param $where
     */
    public function deleteOrd($param)
    {
        try{
            foreach($param as $v){
                $order_sn = Db::name('order')->where('id',$v)->find();
                $account_status = Db::name('account')->where(['order_sn'=>$order_sn['order_sn']])->column('status');
                if($order_sn['status'] == 31 || $order_sn['order_sn'] == 1){
                    $this->commit();
                    return ['code'=>0,'msg'=>'未完成的账单,不可删除'];
                }
                if(in_array(0,$account_status)){
                    $this->commit();
                    return ['code'=>0,'msg'=>'存在未支付流水,不可删除'];
                }else{
                    $this->where('id',$v)->delete();
                }
            }
            $this->commit();
            return ['code'=>1,'msg'=>'删除成功'];
        }catch(\Exception $e){
            $this->rollback();
            return ['code'=>0,'msg'=>'删除失败'.$e->getMessage()];
        }

    }
}
